package game.Actors;

import java.util.ArrayList;

import org.newdawn.slick.Image;
import org.newdawn.slick.geom.Vector2f;
/**
 * This class represents a ricochet bullet in the game.
 * A ricochetbullet will search for new targets when it collides with an enemy.
 * @author Sebastian Isheden and Victor Beer.
 *
 */
public class RicochetBullet extends Bullet{
	private int targetsRemaining;
	private Enemy previousTarget;
	private float bounceRadius;
	/**
	 * Creates a ricochetbullet based on the given parameters.
	 * @param image The image of the bullet.
	 * @param position The position of the bullet.
	 * @param speed The speed of the bullet.
	 * @param direction The direction of the bullet.
	 * @param damage The damage of the bullet.
	 * @param bounceRadius The radius this bullet will be able to find new targets. 
	 * @param targetsRemaining The amount of enemies this bullet will be able to bounce between.
	 * @param previousTarget The target this bullet hit last time. 
	 */
	public RicochetBullet(Image image, Vector2f position, float speed,Vector2f direction, float damage,float bounceRadius,int targetsRemaining,Enemy previousTarget) {
		super(image, position, speed, direction, damage);
		this.bounceRadius = bounceRadius;
		this.targetsRemaining = targetsRemaining;
		this.previousTarget = previousTarget;
	}

	@Override
	protected void explode(Enemy enemy){
		this.isDead = true;
		ArrayList<Enemy> enemies = Enemy.getEnemyList();
		
		for(int i = enemies.size() - 1; i >= 0; i--) {
			if(enemy.equals(enemies.get(i))){
				continue;
			}
			Vector2f enemyPosition = enemies.get(i).position.copy();
		    Vector2f newDirection = enemyPosition.add(new Vector2f(-this.position.x,-this.position.y));
			float distance = newDirection.length();
			if(distance <= this.bounceRadius){
				new RicochetBullet(this.image,this.position.copy(),this.speed,newDirection.copy().normalise(),this.damage,this.bounceRadius,this.targetsRemaining-1,enemy);
				break;
			}
		}
	}
	
	@Override
	protected void checkEnemyCollision(){
		if(targetsRemaining == 0){
			this.isDead = true;
			return;
		}
		ArrayList<Enemy> enemies = Enemy.getEnemyList();
	    for(int i = enemies.size() - 1; i >= 0; i--) {
	    	Enemy enemy = enemies.get(i);
	    	if(isColliding(enemy) && !enemy.equals(previousTarget)) {
	    		enemy.hit(this.damage);
	    		this.explode(enemy);
	    		break;
	    	}
	    }
	
	}
}
